package com.yingside.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.yingside.common.util.ShiroUtil;
import com.yingside.common.util.TreeUtil;
import com.yingside.system.model.Menu;
import com.yingside.system.mapper.MenuMapper;
import com.yingside.system.model.User;
import com.yingside.system.service.IMenuService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author yingside
 * @since 2020-12-30
 */
@Service
public class MenuServiceImpl extends ServiceImpl<MenuMapper, Menu> implements IMenuService {

    @Autowired
    private MenuMapper menuMapper;

    /**
     * 获取当前登陆用户拥有的树形菜单 (admin 账户拥有所有权限.)
     */
    public List<Menu> selectCurrentUserMenuTree() {
        // 从shiro中取出当前登录用户
        User currentUser = ShiroUtil.getCurrentUser();

        return selectMenuTreeByUsername(currentUser.getUsername());
    }

    /**
     * 根据用户名获取该用户拥有的树形菜单
     * @param username 用户名
     * @return         封装好的树状层级关系的Menu集合
     */
    public List<Menu> selectMenuTreeByUsername(String username){
        List<Menu> menus = null;

        if("admin".equals(username)){
            QueryWrapper queryWrapper = new QueryWrapper();
            queryWrapper.orderByAsc("order_num");
            menus = menuMapper.selectList(queryWrapper);
        }
        else{
            menus = menuMapper.selectMenuByUserName(username);
        }

        return toTree(menus);
    }

    /**
     * 将普通的Menu集合转换为树形结构
     */
    private List<Menu> toTree(List<Menu> menuList) {
        return TreeUtil.toTree(menuList, "menuId", "parentId", "children", Menu.class);
    }

    /**
     * 查询所有的menu，并组装层级关系(数据库直接子查询获取)
     * @return 有树状层级关系的Menu集合
     */
    public List<Menu> selectAllTree() {
        return menuMapper.selectAllTree();
    }

    @Override
    public List<Menu> getLeafNodeMenu() {
        List<Menu> menus = selectAllTree();
        return TreeUtil.getAllLeafNode(menus);
    }
}
